/**
 * @Author: easten
 * @Created: 2024-07-21 17:57:08
 * @Description:
 *
 */
import { ModuleCommonProps, PageParams, TreeDataModel } from "_common/DataType";
import { IotDevice, IotDeviceGroup } from "_common/entity";
import React, { useState, useEffect, useMemo } from "react";
import {
  CpuIcon,
  FileDownloadIcon,
  RefreshIcon,
  RemoteWaveIcon,
} from "tdesign-icons-react";
import {
  Button,
  Popconfirm,
  Radio,
  Space,
  Table,
  Tag,
  Tooltip,
  Tree,
  Upload,
  message,
} from "tdesign-react";
import classnames from "classnames";
import TableTitle from "components/common/TableTitle";
import DeviceDrawer from "./DeviceDrawer";
import { ApiDevice, ApiDeviceGroup, ApiTerminal } from "_common/api/iot";
import ExcelJS from "exceljs";
export type IotDeviceCompProps = ModuleCommonProps & {};
const IotDeviceComp: React.FC<IotDeviceCompProps> = (
  props: IotDeviceCompProps
) => {
  const { axios, className } = props;
  const [selectedRowKeys, setSelectedRowKeys] = useState<(string | number)[]>([
    1, 2,
  ]);
  const [loading] = useState<boolean>(false);
  const [deviceList, setDeviceList] = useState<IotDevice[]>([]);
  const [selectedRow, setSelectedRow] = useState<IotDevice>();
  const [pageState, setPageState] = useState<PageParams>({
    pageNum: 1,
    pageSize: 10,
    total: 0,
  });

  const [visible, setVisible] = useState(false);
  const [edit, setEdit] = useState(false);
  const [copy, setCopy] = useState(false);
  const [terminalTree, setTerminalTree] = useState<TreeDataModel[]>([]);
  const [selectNode, setSelectNode] = useState<TreeDataModel | undefined>();
  // 设备分组信息
  const [deviceGroup, setDeviceGroup] = useState<IotDeviceGroup[]>([]);
  const [selectGroup, setSelectGroup] = useState<number>();

  const [files, setFiles] = useState<File[]>([]);
  const apiDevice = new ApiDevice(axios);
  const apiTerminal = new ApiTerminal(axios);
  const apiDeviceGroup = new ApiDeviceGroup(axios);

  function onSelectChange(value: (string | number)[]) {
    setSelectedRowKeys(value);
  }
  useEffect(() => {
    getTree();
    getDeviceGroup();
  }, []);

  const getDeviceList = async () => {
    const response = await apiDevice.getPageList({
      pageNum: pageState.pageNum,
      pageSize: pageState.pageSize,
      terminalId: selectNode?.value,
      dtCode: selectGroup,
    });
    if (response && response.code == 200 && response.data) {
      setDeviceList(response.data.list);
      setPageState({
        ...pageState,
        total: response.data.total,
      });
    } else {
      setDeviceList([]);
    }
  };

  useEffect(() => {
    getDeviceList();
  }, [selectNode, pageState.pageNum, pageState.pageSize, selectGroup]);

  // 删除用户
  const deleteDevice = async (id: number) => {
    const response = await apiDevice.deleteDevice(id);
    if (response && response.code == 200 && response.data) {
      message.success("删除成功");
      getDeviceList();
    }
  };

  // 获取设备分组信息
  const getDeviceGroup = async () => {
    const response = await apiDeviceGroup.getDeviceGroupList();
    if (response && response.code == 200 && response.data) {
      setDeviceGroup(response.data);
      if (response.data.length > 0) {
        setSelectGroup(response.data[0]?.groupCode);
      }
    }
  };

  // 获取结构树
  const getTree = async () => {
    const response = await apiTerminal.getTerminalTree();
    if (response && response.code == 200 && response.data) {
      setTerminalTree(response.data);
    }
  };

  // 导出模板
  const exportExcelTemp = () => {
    const workbook = new ExcelJS.Workbook();
    const sheet = workbook.addWorksheet("设备列表");
    if (selectGroup == 109) {
      sheet.columns = [
        { header: "设备序号（必填）", key: "orderNum", width: 10 },
        { header: "设备编码（必填）", key: "deviceCode", width: 20 },
        { header: "设备名称（必填）", key: "deviceName", width: 20 },
        { header: "产品编码（固定：109）", key: "deviceCode", width: 20 },
        { header: "设备型号", key: "deviceName", width: 20 },
        { header: "油脂容量（必填）", key: "deviceName", width: 20 },
        { header: "加脂周期（必填）", key: "deviceName", width: 20 },
        { header: "加脂次数（必填）", key: "deviceName", width: 20 },
      ];
    } else {
      sheet.columns = [
        { header: "设备序号", key: "orderNum", width: 10 },
        {
          header: "产品编码\n温度：116\n温湿度：112\n烟感111\n水浸：114",
          key: "dtCode",
          width: 30,
        },
        { header: "设备名称", key: "deviceName", width: 20 },
        { header: "设备ID", key: "deviceCode", width: 20 },
        /*  { header: "设备型号", key: "deviceCode", width: 20 },
        { header: "油脂容量", key: "deviceCode", width: 20 },
        { header: "加脂周期", key: "deviceCode", width: 20 },
        { header: "工作行程", key: "deviceCode", width: 20 }, */
      ];
    }

    workbook.xlsx.writeBuffer().then((buffer: any) => {
      writeFile("设备导入模板", buffer);
    });
  };
  const writeFile = (fileName: any, content: any) => {
    const link = document.createElement("a");
    const blob = new Blob([content], {
      type: "application/vnd.ms-excel;charset=utf-8;",
    });
    link.download = fileName;
    link.href = URL.createObjectURL(blob);
    link.click();
  };

  const renderLabel = (node: any) => {
    let data = node.data;
    if (data.type == 1) {
      return (
        <Tag
          theme="warning"
          variant="outline"
          icon={<CpuIcon color="#EF9735" />}
          size="small"
        >
          网关：{data.label}
        </Tag>
      );
    } else {
      return (
        <Tag
          theme="success"
          variant="outline"
          icon={<RemoteWaveIcon color="#1AA84F" />}
          size="small"
        >
          终端：{data.label}
        </Tag>
      );
    }
  };

  const treeNode = useMemo(() => {
    return (
      <Tree
        data={terminalTree}
        activable
        hover
        transition
        label={renderLabel}
        className="ml-0"
        onActive={(e, c) => {
          if (e.length == 0) {
            setSelectNode(undefined);
          } else {
            setSelectNode(c.node as any);
          }
        }}
      />
    );
  }, [terminalTree, selectNode]);

  return (
    <div className={classnames(className, "flex", "flex-row h-full")}>
      <div
        style={{
          width: 300,
          borderRight: "1px solid var(--td-border-level-1-color)",
        }}
        className="h-full"
      >
        <TableTitle text="终端信息" />
        <div className="pt-4 pr-5 pl-0">{treeNode}</div>
      </div>
      <div
        className={classnames("pl-5")}
        style={{ width: "calc(100% - 300px)" }}
      >
        <div className="flex flex-row justify-between mb-4">
          <div className="flex flex-row">
            <TableTitle text="设备列表" />
            <Radio.Group
              variant="outline"
              value={selectGroup}
              onChange={(v) => setSelectGroup(v as number)}
            >
              {/* <Radio.Button value={undefined}>全部</Radio.Button> */}
              {deviceGroup?.map((item) => {
                return (
                  <Radio.Button key={item.groupCode} value={item.groupCode}>
                    {item.groupName}
                  </Radio.Button>
                );
              })}
            </Radio.Group>
          </div>
          <Space size={5}>
            <Button
              onClick={() => {
                // 判断是否选择了
                if (!selectNode || selectNode.type == 1) {
                  message.error("请选择终端");
                  return;
                }

                if (!selectGroup) {
                  message.error("请选择产品类型");
                  return;
                }
                setVisible(true);
                setEdit(false);
              }}
            >
              添加设备
            </Button>
            <Upload
              files={files}
              onChange={(files) => {
                setFiles(files);
              }}
              theme="custom"
              beforeUpload={async (file) => {
                // 提交到后台
                // file 转换为 IFormFile
                if (file == null) return false;
                var formData = new FormData();
                // @ts-ignore
                formData.append("file", file.raw);
                const response = await apiDevice.import(
                  selectNode?.value!,
                  selectGroup!,
                  formData
                );
                if (response && response.code == 200 && response.data) {
                  message.success("上传成功");
                  getDeviceList();
                }
                return true;
              }}
              accept=".xls,.xlsx"
            >
              <Button
                theme="primary"
                onClick={(e) => {
                  if (!selectNode || selectNode.type == 1) {
                    message.error("请选择终端");
                    e.stopPropagation();
                    return;
                  }
                  if (!selectGroup) {
                    message.error("请选择需要导入的设备类型");
                    e.stopPropagation();
                    return;
                  }
                }}
              >
                批量上传
              </Button>
            </Upload>
            <Tooltip content="下载模板">
              <Button
                icon={<FileDownloadIcon />}
                variant="outline"
                onClick={() => {
                  // 下载模板
                  exportExcelTemp();
                }}
              ></Button>
            </Tooltip>
            <Button
              icon={<RefreshIcon />}
              variant="outline"
              onClick={() => {
                getDeviceList();
              }}
            ></Button>
          </Space>
        </div>
        <Table<IotDevice>
          bordered
          columns={[
            {
              align: "left",
              width: 120,
              ellipsis: true,
              colKey: "orderNo",
              title: "序号",
              // cell: ({ rowIndex }) => {
              //   // let _index = (pageState.pageNum - 1) * pageState.pageSize + rowIndex + 1;
              //   // return <span>{_index}</span>;
              // },
            },
            {
              align: "left",
              ellipsis: true,
              colKey: "deviceName",
              title: "设备名称",
            },
            {
              align: "left",
              ellipsis: true,
              colKey: "deviceCode",
              title: "设备ID",
            },
            {
              align: "center",
              ellipsis: true,
              colKey: "group?.groupName",
              title: "所属产品",
              cell: ({ row }) => {
                return (
                  <Tag theme="primary" variant="light-outline">
                    {row.group?.groupName}
                  </Tag>
                );
              },
            },
            {
              align: "center",
              fixed: "right",
              width: 220,
              colKey: "op",
              title: "操作",
              cell({ row }) {
                return (
                  <>
                    <Button
                      theme="success"
                      variant="text"
                      onClick={() => {
                        setVisible(true);
                        setEdit(true);
                        setSelectedRow(row);
                      }}
                    >
                      编辑
                    </Button>
                    <Button
                      theme="success"
                      variant="text"
                      onClick={() => {
                        setVisible(true);
                        setCopy(true);
                        setEdit(false);
                        setSelectedRow(row);
                      }}
                    >
                      复制
                    </Button>
                    <Popconfirm
                      content="确认删除吗"
                      destroyOnClose
                      placement="top"
                      showArrow
                      theme="default"
                      onConfirm={() => deleteDevice(row.id!)}
                    >
                      <Button theme="primary" variant="text">
                        删除
                      </Button>
                    </Popconfirm>
                  </>
                );
              },
            },
          ]}
          loading={loading}
          data={deviceList}
          rowKey="id"
          selectedRowKeys={selectedRowKeys}
          verticalAlign="middle"
          hover
          onSelectChange={onSelectChange}
          pagination={{
            pageSize: pageState.pageSize,
            total: pageState.total,
            current: pageState.pageNum,
            showJumper: true,
            onCurrentChange(current) {
              setPageState({
                ...pageState,
                pageNum: current,
              });
            },
            onPageSizeChange(size) {
              setPageState({
                ...pageState,
                pageSize: size,
              });
            },
          }}
        />
      </div>
      <DeviceDrawer
        groupCode={selectGroup}
        open={visible}
        axios={axios}
        edit={edit}
        copy={copy}
        terminal={selectNode}
        value={selectedRow}
        onSuccess={() => {
          setVisible(false);
          getDeviceList();
        }}
      />
    </div>
  );
};
export default IotDeviceComp;
